package gamewalletlogic

import (
	"context"
	"go.uber.org/zap"
	gameuserlogic "navi-mumbai/app/rpc/game/internal/logic/gameuser"
	"navi-mumbai/app/rpc/game/internal/svc"
	"navi-mumbai/app/rpc/game/pb"
	"navi-mumbai/common/key/walletkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/third/game/wz"
	"net/http"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserTransferFromGWalletLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserTransferFromGWalletLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserTransferFromGWalletLogic {
	return &UserTransferFromGWalletLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 从G端钱包转账到B端钱包
func (l *UserTransferFromGWalletLogic) UserTransferFromGWallet(in *pb.UserTransferFromGWalletReq) (*pb.UserTransferFromGWalletResp, error) {
	defer utils.RecoverPanic()

	var rsp *pb.GetOpenIdByUidResp
	var err error
	var in1 pb.GetOpenIdByUidReq
	in1.Uid = in.Uid
	in1.ProviderId = in.ProviderId
	rsp, err = gameuserlogic.NewGetOpenIdByUidLogic(l.ctx, l.svcCtx).GetOpenIdByUid(&in1)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	wzReq := wz.TransferFromGameReq{
		Uid:      strconv.FormatInt(rsp.OpenId, 10),
		Amount:   in.MoneyAmount,
		TradeNo:  strconv.FormatInt(in.FlowNo, 10),
		Currency: walletkey.GetGameCurrency(in.ProviderId, in.MoneyType),
		User:     rsp.Nickname,
	}
	l.Logger.Infof("UserTransferFromGWallet Uid %s Amount %s TradeNo %s Currency %s User %s ", wzReq.Uid, wzReq.Amount,
		wzReq.TradeNo, wzReq.Currency, wzReq.User)
	var wzResp *wz.TransferFromGameResp
	wzResp, err = wz.Hc.TransferFromGame(&wzReq)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}
	var resp pb.UserTransferFromGWalletResp
	resp.State = walletkey.UserWalletTransferFromGameFlowStateFailed

	if wzResp.Code == http.StatusOK {
		resp.State = walletkey.UserWalletTransferFromGameFlowStateSuccess
		resp.ExternalFlowNo = wzResp.Data.GTxId
		resp.MoneyType = walletkey.GetMoneyTypeFromGame(in.ProviderId, wzResp.Data.Currency)
		resp.NewBalance = wzResp.Data.NewBalance
		resp.OldBalance = wzResp.Data.OldBalance
	} else {
		resp.ErrMsg = strconv.FormatInt(int64(wzResp.Code), 10)
		l.Logger.Errorf("UserTransferFromGWallet State %d ExternalFlowNo %s MoneyType %d NewBalance %s OldBalance %s ", resp.State,
			resp.ExternalFlowNo, resp.MoneyType, resp.NewBalance, resp.OldBalance)
	}
	return &resp, nil
}
